<template>
	<view class="containt">
	    <view class="cardbox">
	      <view class="flexCenterSpaceBetween mb20">
	        <view class="title">选择类别</view>
	      </view>
	      <view class="typecardbox">
	        <view
						v-for="item in typelist1"
	          :class="{ targetactive: activetype == item.name }"
	          class="flexCenterCenter typecard"
	          ::key="item"
						@tap="handleChangeType(item)"
	        >
	          <image
	            class="yuanimg"
	            src="@/static/img/sale1.png"
	            mode="widthFix"
	          ></image>
	          <view class="yuantext">{{ item.name }}</view>
	        </view>
	      </view>
	    </view>
	    <view class="cardbox">
	      <view class="title mb20">所属品牌</view>
	      <view class="flex">
	        <view class="targettab targettabbg flexCenterCenter" v-if="isselpinpai">
	          <image
	            class="yuanimg"
	            :src="`${baseimgURL}${selpinpai.brandLogo}`"
	            mode="widthFix"
	          ></image>
	          <text class="">{{selpinpai.brandName}}</text>
	        </view>
	        <view
	          class="targettab flexCenterCenter"
	          @tap="jumppage('/pages/sale/selectpai')"
	        >
	          <image
	            class="pingpaiimg"
	            src="@/static/img/sale2.png"
	            mode="widthFix"
	          ></image>
	          <view class="flex">
							全部品牌
	            <u-icon name="arrow-right"></u-icon>
	          </view>
	        </view>
	      </view>
	    </view>
	    <view class="cardbox">
	      <view class="title mb20">商品图片</view>
	      <view class="flex flexupload">
					<view v-if="!isAuth" class="upload-layer" @tap="handleClickLayer"></view>
					<view class="upload-container">
						<view class="photobox" v-for="(item, idx) in picList" ::key="item">
							<u-upload
								:fileList="state['fileList' + idx]"
								@afterRead="afterRead($event, idx)"
								@delete="deletePic($event, idx)"
								name="file"
								:maxCount="1"
								width="155"
								height="155"
							>
								<view class="photocard">
									<image
										class="photoimg"
										mode="widthFix"
										:src="`${baseimgURL}${item.imgUrl}`"
									>
									</image>
									<view class="mt10 describe">{{item.label}}</view>
								</view>
							</u-upload>
						</view>
					</view>
	      </view>
	    </view>
	    <view class="cardbox">
	      <view class="title mb20">选择鉴定师</view>
	      <view class="flex chengseflexbox">
	        <view
	          class="chengsebox"
	          :class="{ targetactive: activetarget == item.title }"
	          v-for="item in jiandinglist"
	          ::key="item"
						@tap="handletype2(item)"
	        >
	          <view class="chengseTitle">{{item.title}}</view>
	          <view class="chengseDescription">{{item.name}}</view>
	        </view>
	      </view>
	      <view>鉴定费：<text class="moneytext">¥{{money}}</text> </view>
	    </view>
	    <view class="cardbox flexYCenter"  style="margin-bottom: 60rpx;">
	      <view class="title mb20">备注说明</view>
	      <u-textarea
	        v-model="applyRemark"
	        placeholder="备注需要补充的说明"
	        ref="textarea"
	      ></u-textarea>
	    </view>
			<!-- 吸底工具栏 -->
			<view class="flex " style="width: 100%;height: 90rpx;background: #fff;position: fixed;left: 0;bottom: 100rpx;font-size: 22rpx;padding-left: 34rpx;display: flex;align-items: center">
				<checkbox-group @change="handleYes($event)">
					<label>
						<checkbox value="isConsent.value" checked="true" style="transform:scale(0.7)" />使用即表示同意
					</label>
				</checkbox-group>
				<text style="font-weight: 600;" @click="clickViewProtocol('/pages/me/mine')">《奢收多客户鉴定协议》</text>
			</view>
	        <view
	        class="toolbar-height"
	        :style="{ paddingBottom: safeAreaInsets?.bottom+30 + 'px' }"
	      ></view>
	      <view
	        class="toolbar"
	        :style="{ paddingBottom: safeAreaInsets?.bottom +30+ 'px' }"
	      >
	    <view class="button-grounps">
	      <view @tap="submit" class="button payment-button">
					<view class="title">提交申请</view>
					<view class="describe">免费上门取件鉴定</view>
			  </view>
	    </view>
	    </view>

			<gorenzheng ref="renRef" @gorenpage="gorenpage"></gorenzheng>
	  </view>
</template>

<script lang="ts" setup>
	import { ref, reactive, onMounted } from "vue"
	import { onLoad } from "@dcloudio/uni-app"
	import { fetchConfigList } from '../../api/order'
	import { createJainding } from '../../api/jianding'
	import { uploadAction } from '../../config/index'
	import ORDERCONSTANT from '../../constant/order'
	import { baseimgURL } from '@/config'
	import { getAuthStatus } from '@/utils/common'
	import gorenzheng from "@/components/gorenzheng"
	import payUtil from '@/utils/pay'
	
	const activetype = ref("")
	const activetarget = ref("")
	const isConsent = ref(true)
	const isselpinpai = ref(false)
	const selpinpai = ref(null)
	const applyRemark = ref('')
	const picListLen = ref(9)
	const picList = ref([])
	const money = ref(0)
	const renRef = ref(null)
	const isAuth = ref(false)
	let wxCode = ''

	onLoad(async () => {
		const res = await wx.login()
		wxCode = res.code	
	})
	
	const handleYes = () => {
	  isConsent.value = !isConsent.value;
	}
	const handletype2 = (item) => {
	  activetarget.value = item.title;
		money.value = item.money
	}
	const state = reactive({
		fileList0: [],
		fileList1: [],
		fileList2: [],
		fileList3: [],
		fileList4: [],
		fileList5: [],
		fileList6: [],
		fileList7: [],
		fileList8: [],
	})
	
	// 删除图片
	const deletePic = (event, index) => {
		state['fileList' + index] = []
	}
	const clickViewProtocol = (url) => {
		let allAgreement = JSON.parse(uni.getStorageSync('allAgreement')) 
		uni.navigateTo({ url: url+'?id='+ allAgreement[2].value.id+'&title='+'奢收多客户鉴定协议'});
	}
	// 新增图片
	const afterRead = async (event, index) => {
		const fList = state['fileList' + index]
	  // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
	  let lists = [].concat(event.file);
	  let fileListLen = fList.length;
	  lists.map((item) => {
	    fList.push({
	      ...item,
	      status: "uploading",
	      message: "上传中",
	    })
	  })
	  for (let i = 0; i < lists.length; i++) {
	    const result = await uploadFilePromise(lists[i].url)
	    let item = fList[fileListLen]
	    fList.splice(fileListLen, 1, {
	      ...item,
	      status: "success",
	      message: "",
	      url: `${baseimgURL}${result.data.url}`,
	    })
	    fileListLen++
	  }
	}

	// 去认证
	const gorenpage = () => {
		let userinfo = uni.getStorageSync("userinfo") ? JSON.parse(uni.getStorageSync("userinfo"))  : {}
		if (userinfo.memberCertificate?.auditStatus === 2) {
			uni.navigateTo({
				url: "/pages/me/authentication?id=" + userinfo.id,
			})
		} else {
			uni.navigateTo({
				url: "/pages/me/authentication" 
			})
		}
	}

	const handleClickLayer = () => {
		renRef.value.maopen()
	}
	
	const uploadFilePromise = (url) => {
		const token = uni.getStorageSync("token")
		const token_type = uni.getStorageSync("token_type")
	  return new Promise((resolve, reject) => {
	    let a = uni.uploadFile({
	      url: uploadAction,
	      filePath: url,
	      name: "file",
				header: {
					"content-type": "application/json",
					"Authorization": `${token_type} ` + `${token}`,
				},
				formData: {
					typeCode: 'applyRecycle',
					fieldProperty: 'productPicture',
				},
	      success: (res) => {
					const data = JSON.parse(res.data)
					resolve(data)
	      },
	    });
	  });
	}
	const jumppage = (url) => {
		let userinfo = uni.getStorageSync("userinfo") ? JSON.parse(uni.getStorageSync("userinfo")) : {}
		// 认证成功
		if (userinfo.memberCertificate?.auditStatus === 1) {
			uni.navigateTo({
				url: url,
				events: {
					// 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
					acceptDataFromOpenedPage: function(data) {
						if(data){
							isselpinpai.value = true
							console.info('已选择品牌: ', JSON.parse(data.data))
							selpinpai.value = JSON.parse(data.data)?.item ?.name
						}
					},
				},
			})
		} else {
			renRef.value.maopen()
		}
	}
	const typelist1 = ORDERCONSTANT.GOODS_CATEGORY
	const jiandinglist = ref([
	  { title: "高级鉴定师", name: "5年以上鉴定经验", money: null },
	  { title: "资深鉴定师", name: "8年以上鉴定经验", money: null },
	])
	
	const handleChangeType = async (item) => {
		activetype.value = item.name
		try {
			const { code, msg, data } = await fetchConfigList([item.value])
			if (code === '1') {
				const content = JSON.parse(data[0].configContent)
				picListLen.value = content.length
				picList.value = content
			} else {
				uni.showToast({
					title: msg,
					icon: 'none'
				})
			}
		} catch(err) {
			console.error(err)
		}
	}
	
	const getAppraisalFeeConfig = async (key) => {
		try {
			const res = await fetchConfigList([key])
			if (res.code === '1') {
				const configContent = res.data[0].configContent
				const content = JSON.parse(configContent)
				const data = content[5]
				jiandinglist.value[0].money = Number(data.value.value1)
				jiandinglist.value[1].money = Number(data.value.value2)		
			} else {
				uni.showToast({
					title: msg,
					icon: 'none'
				})
			}
		} catch(err) {
			console.error(err)
		}
	}
	
	const submit = async () => {
	  try {
			if (!activetype.value) {
				uni.showToast({
					title:'请选择类别',
					icon:'none'
				})
				return
			}
			if (!selpinpai.value) {
				uni.showToast({
					title:'请选择品牌',
					icon:'none'
				})
				return
			}
			if (!activetarget.value) {
				uni.showToast({
					title:'请选择鉴定师',
					icon:'none'
				})
				return
			}
			const fileList = []
			for (let key in state) {
				if (state[key] && state[key][0]) {
					fileList.push(state[key][0].url.replace(`${baseimgURL}/`, '/'))
				}
			}
			if (fileList.length > 2) {
				let money = null
				jiandinglist.value.map(item => {
					if (activetarget.value === item.title) {
						money = item.money
					}
				})
				const params = {
				  form: {
				    category: activetype.value, // 品类
				    brandId: selpinpai.value?.id, // 品牌
				    productPicture: fileList.join(','), // 图片
				    appraiseRank: activetarget.value, // 鉴定级别
						payAmount: money, // 鉴定费
				    applyRemark: applyRemark.value, // 描述
				  }
				}
				const { code, msg, data } = await createJainding(params)
				if (code === '1') {
					uni.showLoading({
						title: '下单成功,请支付',
						mask: true
					})
					payUtil.getPrepayOrder(data, wxCode)
				} else {
				  uni.showToast({ icon: "none", title: msg })
					setTimeout(() => {
						uni.reLaunch({ url: '/pages/jianding/list' })
					}, 500)
				}
			} else {
				uni.showToast({ icon: "none", title: '请上传前3张图片' })
			}
	  } catch(err) {
	    console.error(err)
	  }
	}
	
	onMounted(() => {
		isAuth.value = getAuthStatus()
		handleChangeType({name: '箱包', value: 'xiangbao_recyle'})
		getAppraisalFeeConfig('special_content')
	})
</script>

<style lang="scss" scoped>
	.containt {
	  padding: 15rpx 22rpx;
	}
	.button-grounps{
		display: flex;
		justify-content: center;
		text-align: center;
		height: 85rpx;
		font-size: 13px;
		color: #fff;
		.button {
		  width: 720rpx;
		  margin: 0 10rpx;
		  border-radius: 72rpx;
		  padding: 10rpx 0rpx;
		}
		.payment-button {
		  background: #953b82;
		  border-radius: 8rpx;
		  .title{
			  font-size: 27rpx;
			  font-weight: 600;
		  }
		  .describe{
			  font-size: 22rpx;
			  font-weight: 400;
			  opacity: .4;
		  }
		}
	}
	
	.cardbox {
	  background: #ffffff;
	  border-radius: 14rpx;
	  padding: 22rpx;
	  margin-bottom: 15rpx;
	  .info{
		  font-size: 24rpx;
		  font-family: PingFangSC, PingFang SC;
		  font-weight: 400;
		  color: #666666;
		  line-height: 33rpx;
		  margin-right: 7rpx;
	  }
	  .title {
	    font-size: 27rpx;
	    font-weight: 600;
	    color: #000000;
	  }
	
	  .typecardbox {
	    display: flex;
	    flex-wrap: wrap;
	    width: 100%;
	    /* justify-content: space-between; */
	    /* &::after {
	      content: "";
	      width: calc(25% - 15rpx);
	    } */
	    .typecard {
	      border-radius: 7rpx;
	      border: 2rpx solid #e6e6e6;
	      text-align: center;
	      width: calc((100% - 60rpx) / 4);
	      margin-right: 20rpx;
	      margin-bottom: 10rpx;
	      padding: 5rpx 0;
	      box-sizing: border-box;
	      &:nth-child(4n + 4) {
	        margin-right: 0;
	      }
	    }
	
	    .yuantext {
	      white-space: nowrap;
		  font-size: 24rpx;
		  font-weight: 400;
		  color: #333333;
		  line-height: 33rpx;
	    }
	  }
	  .yuanimg {
	    width: 52rpx;
	    height: 52rpx;
	    border-radius: 33rpx;
	    margin-right: 13rpx;
	  }
	  .pingpaiimg {
	    width: 52rpx;
	    height: 52rpx;
	    border-radius: 33rpx;
	    margin-right: 13rpx;
	    margin-left: -40rpx;
	    border: 2rpx solid #e6e6e6;
	  }
	  .noselectpingpaiimg {
	    width: 52rpx;
	    height: 52rpx;
	    border-radius: 33rpx;
	    margin-right: 13rpx;
	    border: 2rpx solid #e6e6e6;
	  }
	  .targettab {
	    flex: 1;
	    height: 63rpx;
	    border-radius: 7rpx;
	    border: 2rpx solid #e6e6e6;
	    font-size: 22rpx;
	    font-weight: 400;
	  }
	  .targettabbg {
	    background: #f6edf4;
	    color: #953b82;
	  }
	  .notargettab {
	    padding: 11rpx;
	  }
	  .targetactive {
	    background: #f6edf4;
	    color: #953B82;
	  }
	  .targettab:nth-child(1) {
	    margin-right: 20rpx;
	  }
	  .flexupload {
	    position: relative;
	  }
		.upload-container {
			display: flex;
			flex-wrap: wrap;
		}
		.flexupload .upload-layer {
			position: absolute;
			width: 100%;
			height: 100%;
			z-index: 999;
		}
	  .photobox {
	    width: calc((100% - 60rpx) / 4);
	    margin-right: 20rpx;
	    box-sizing: border-box;
	    margin-top: 20rpx;
		margin-bottom: 10rpx;
	    &:nth-child(4n + 4) {
	      margin-right: 0;
	    }
	    .photoimg {
	      width: 73rpx;
	      height: 73rpx;
	    }
	    .photocard {
	      width: 155rpx;
	      height: 155rpx;
	      background: #f0f0f0;
	      border-radius: 7rpx;
	      display: flex;
	      align-items: center;
	      justify-content: space-between;
	      flex-direction: column;
		  padding-top: 47rpx;
		  box-sizing: border-box;
		  .describe{
			  font-size: 24rpx;
			  color: #ffffff;
			  width: 100%;
			  text-align: center;
			  height: 38rpx;
			  background: linear-gradient(180deg, rgba(255,255,255,0) 0%, rgba(0,0,0,0.8) 100%);
			  opacity: .4;
		  }
	    }
	  }
	  .chengseflexbox {
	    flex-wrap: wrap;
	    .chengsebox {
	      margin-right: 15rpx;
	      width: calc((100% - 15rpx) / 2);
	      height: 118rpx;
	      vertical-align: middle;
	      border-radius: 7rpx;
	      border: 2rpx solid #e6e6e6;
	      box-sizing: border-box;
	      margin-bottom: 13rpx;
	      padding: 22rpx;
	      &:nth-child(2n) {
	        margin-right: 0;
	      }
		  .chengseTitle{
			  color: #666666;
			  font-weight: 600;
			  font-size: 25rpx;
			  margin-bottom: 7rpx;
		  }
		  .chengseDescription{
			  color: #666666;
			  font-size: 25rpx;
		  }
	    }
	  }
	}
	.moneytext {
	  font-size: 24rpx;
	  font-weight: 600;
	  color: #e6542b;
	}
</style>